package com.stm.bi.report;

import com.stm.base.api.RegionRemoteService;
import com.stm.base.dto.vo.DictVO;
import com.stm.base.dto.vo.RegionDetailVO;
import com.stm.base.provider.DictionaryProvider;
import com.stm.bi.constant.DictionaryConstants;
import com.stm.bi.dto.query.RegionalSaleQry;
import com.stm.bi.dto.query.RegionalSaleQuery;
import com.stm.bi.dto.vo.CustomerTurnoverRankVO;
import com.stm.bi.dto.vo.RegionalCustomerToBVO;
import com.stm.bi.model.Chart;
import com.stm.framework.core.util.FileResourceLoader;
import com.stm.framework.dbcp.JdbcService;
import com.stm.framework.dto.Response;
import com.stm.ucenter.api.BizCustomerRemoteService;
import com.stm.ucenter.dto.query.BizCustomerListQry;
import com.stm.ucenter.dto.vo.BizCustomerVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


/**
 * @author zp
 * @date 2025/2/14 9:09
 */
@Component
public class RegionalTurnoverQueryExe extends AbsChartQueryExe<RegionalSaleQuery, RegionalCustomerToBVO> {
    @Resource
    private JdbcService jdbcService;

    @Resource
    private BizCustomerRemoteService bizCustomerRemoteService;

    @Resource
    private DictionaryProvider dictionaryProvider;

    @Resource
    private RegionRemoteService regionRemoteService;


    @Override
    public RegionalCustomerToBVO query(Long orgId, String orgNo, RegionalSaleQuery regionalSaleQry) {
        RegionalCustomerToBVO vo = new RegionalCustomerToBVO();
        List<CustomerTurnoverRankVO> customerTurnoverRanks = new ArrayList<>();
        // 根据部门id查询该部门下所有B端客户信息
        BizCustomerListQry bizQry = new BizCustomerListQry();
        bizQry.setChildId(regionalSaleQry.getDeptId());
        Response<List<BizCustomerVO>> bizResponse = bizCustomerRemoteService.selectList(bizQry);
        if (!bizResponse.isSuccess() || bizResponse.getData().isEmpty()) {
            return vo;
        }
        List<BizCustomerVO> bizCustomers = bizResponse.get();
        List<String> bizCodes = bizCustomers.stream().map(BizCustomerVO::getCode).filter(Objects::nonNull).collect(Collectors.toList());
        // 客户类型字典
        List<DictVO> dictList = dictionaryProvider.selectList(DictionaryConstants.BIZ_CUSTOMER_TYPE);
        // 查全部
        List<Map> maps = getToBCustomerList(bizCustomers, bizCodes,orgId);
        if (maps.isEmpty()) {
            return vo;
        }
        maps.sort(Comparator.comparing((Map m) -> ((BigDecimal) m.get("number_of_dealing"))).reversed());
        maps = maps.stream().filter(m -> m.get("type") != null).collect(Collectors.toList());
        //总销量
        double totalQty = maps.stream().map(m -> (BigDecimal) m.get("number_of_dealing")).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();

        List<Map> finalMaps = new ArrayList<>();
        List<Map> res = new ArrayList<>();
        if (regionalSaleQry.getRegionCode() == null || regionalSaleQry.getRegionCode().isEmpty()) {
            // 全国
            vo.setRegionName("全国")
                    .setSalesVolume(BigDecimal.valueOf(totalQty))
                    .setProportion(BigDecimal.valueOf(100))
                    .setSalesGrade("1");
            res = maps.subList(0, Math.min(5, maps.size()));
            finalMaps = maps;
        } else {
            Response<RegionDetailVO> regionDetailVOResponse = regionRemoteService.selectById(Long.valueOf(regionalSaleQry.getRegionCode()));
            if (regionDetailVOResponse.isSuccess() && regionDetailVOResponse.getData() != null) {
                vo.setRegionName(regionDetailVOResponse.getData().getName());
            }

            // 具体省份
            List<Map> provinceMaps = maps.stream().filter(e -> e.get("provinceCode").equals(Long.valueOf(regionalSaleQry.getRegionCode()))).collect(Collectors.toList());
            provinceMaps = provinceMaps.stream().filter(m -> m.get("type") != null).collect(Collectors.toList());
            // 总销量
            double provinceQty = provinceMaps.stream().map(m -> (BigDecimal) m.get("number_of_dealing")).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();
            finalMaps = provinceMaps;
            res = provinceMaps.subList(0, Math.min(5, provinceMaps.size()));
            // 设置选中省份内容
            // 排名
            Map<String, BigDecimal> provinceTotalQtyMap = maps.stream()
                    .collect(Collectors.groupingBy(
                            m -> ((Long) m.get("provinceCode")).toString(),
                            Collectors.reducing(
                                    BigDecimal.ZERO,
                                    m -> (BigDecimal) m.get("number_of_dealing"),
                                    BigDecimal::add
                            )
                    ));
            // 按销量倒序排序
            provinceTotalQtyMap = provinceTotalQtyMap.entrySet().stream()
                    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue,
                            LinkedHashMap::new
                    ));
            Map<String, BigDecimal> finalProvinceTotalQtyMap = provinceTotalQtyMap;
            // 计算排名
            int grade = IntStream.range(0, finalProvinceTotalQtyMap.size())
                    .filter(i -> finalProvinceTotalQtyMap.keySet().toArray(new String[0])[i].equals(regionalSaleQry.getRegionCode()))
                    .findFirst()
                    .orElse(-1);
            vo.setRegionCode(regionalSaleQry.getRegionCode())
                    .setSalesVolume(BigDecimal.valueOf(provinceQty))
                    .setProportion(BigDecimal.valueOf(100 * provinceQty / totalQty).setScale(2, RoundingMode.HALF_UP));
            if (grade >= 0) {
                vo.setSalesGrade(grade + 1 + "");
            }
        }
        Chart chart = new Chart();
        List<List<Object>> datas = new ArrayList<>();
        List<String> items = chart.getItems();
        // 全国或省份总成交量
        double provinceTotalQty = finalMaps.stream().filter(e -> e.get("number_of_dealing") != null).map(m -> m.get("number_of_dealing")).mapToDouble(e -> ((BigDecimal) e).doubleValue()).sum();
        // 客户占比情况
        Map<Object, List<Map>> type = finalMaps.stream().collect(Collectors.groupingBy(m -> m.get("type")));
        for (DictVO dict : dictList) {
            items.add(dict.getLabel());
            List<Object> data = new ArrayList<>();
            data.add(dict.getLabel());
            // 成交量
            List<Map> subMaps = type.getOrDefault(dict.getValue(), Collections.emptyList());
            double sum = subMaps.stream()
                    .mapToDouble(subMap -> Optional.ofNullable((BigDecimal) subMap.get("number_of_dealing"))
                            .map(BigDecimal::doubleValue)
                            .orElse(0.0)) // 或者其他默认值
                    .sum();
            data.add(sum);
            // 成交量占比
            if (provinceTotalQty != 0) {
                data.add(BigDecimal.valueOf(100 * sum / provinceTotalQty).setScale(2, RoundingMode.HALF_UP));
            } else {
                data.add(BigDecimal.ZERO);
            }

            datas.add(data);
        }
        chart.setDatas(datas);
        vo.setChart(chart);

        for (Map re : res) {
            BigDecimal qty = (BigDecimal) re.get("number_of_dealing");
            if (qty.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            if (!bizCustomers.isEmpty()) {
                // 设置客户信息
                CustomerTurnoverRankVO customerTurnoverRank = new CustomerTurnoverRankVO();
                bizCustomers.stream().filter(e -> e.getCode().equals(re.get("customer_code"))).findFirst().ifPresent(e -> {
                    customerTurnoverRank.setName(e.getName())
                            .setType(e.getType())
                            .setTurnover(qty);
                    customerTurnoverRanks.add(customerTurnoverRank);
                });
            }
        }
        // 确保 productStyleData 中有 5 个对象，不足的部分补充空对象
        int requiredLength = 5;
        if (!customerTurnoverRanks.isEmpty()) {
            while (customerTurnoverRanks.size() < requiredLength) {
                customerTurnoverRanks.add(new CustomerTurnoverRankVO());
            }
        }
        vo.setCustomerTurnoverRank(customerTurnoverRanks);
        return vo;
    }

    public List<Map> getToBCustomerList(List<BizCustomerVO> bizCustomers,List<String> bizCodes, Long orgId) {
        // 查全部
        String year = String.valueOf(LocalDate.now().getYear());
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM ads_base_biz_customer WHERE  org_id = ")
                .append(orgId)
                .append(" and year = ")
                .append(year);
        if (ObjectUtils.isNotEmpty(bizCodes)){
            sql.append(" and customer_code in (");
            for (String bizCode : bizCodes) {
                sql.append("\"")
                        .append(bizCode)
                        .append("\"")
                        .append(",");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
        }
//        sql.append("group by customer_id ORDER BY number_of_dealing");
        List<Map> maps = jdbcService.selectList(sql.toString(), new Object[]{});

        // 给map赋值省份id、省份名称、客户类型和合作类型、新老客
        if (ObjectUtils.isNotEmpty(bizCustomers)) {
            for (Map map : maps) {
                bizCustomers.stream().filter(e -> e.getCode().equals(map.get("customer_code"))).findFirst().ifPresent(biz -> {
                    map.put("provinceCode", biz.getProvinceId());
                    map.put("provinceName", biz.getProvinceName());
                    map.put("type", biz.getType());
                    map.put("newOrOld", biz.getRemark());
//                map.put("coopType", biz.getCoopType());
                });
            }
        }
        maps = maps.stream().filter(e -> ObjectUtils.isNotEmpty(e.get("provinceCode"))).collect(Collectors.toList());
        return maps;
    }

    @Override
    public String getReportName() {
        return "ToB区域成交量";
    }
}
